import axios from 'axios';

axios.defaults.timeout = 100000;
// axios.defaults.headers.Authorization = 'Bearer ';
// const version = app_config.VERSION;

// 请求拦截器
axios.interceptors.request.use(
  config => {
    config.headers['Access-Control-Allow-Origin'] = '*';

    config.withCredentials = true;
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

// 响应拦截器
axios.interceptors.response.use(
  res => {
    const { responseType } = res.config;
    if (responseType === 'blob') {
      return Promise.resolve(res.data);
    }
    const { resCode, errorDescription, resMessage } = res.data;
    if (resCode !== 0) {
      try {
        console.error(errorDescription)
      }catch(err) {
        console.error(err)
      }
      return Promise.reject(resMessage || errorDescription);
    }
    return Promise.resolve(res.data);
  },
  error => {
    return Promise.reject(error);
  },
);

// export default axios;
const request = ({ url, data = {}, type = 'get', exheaders = {}, raw = false, ...extra }) => {
  if (typeof data === 'string') {
    exheaders = { 'Content-Type': 'application/x-www-form-urlencoded', ...exheaders };
  }
  if (type === 'get') {
    return axios.get(url, {
      params: data,
      headers: exheaders,
      ...extra,
    });
  }

  return axios[type](url, raw ? data : { data }, {
    headers: Object.assign({}, exheaders),
    ...extra,
  });
};

export default request;
